import { 
    Message,
    MsgType,
    Room,
    Contact,
} from 'wechaty'
import fs = require('fs')

export class MessageHandler {

    msg: Message
    contact: Contact
    content: string
    msgType: MsgType
    room: Room | null

    constructor(msg: Message) {

        this.msg = msg
        this.contact = msg.from()
        this.content = msg.content()
        this.msgType = msg.type()
        this.room = msg.room()
        this.handle()

    }

    async handle() {

        // if (this.msgType === MsgType.TEXT) {
        //     this.msg.say(this.content)
        // }

        if (this.msgType === MsgType.IMAGE) {
            let filename = `tmp/img/${this.msg.filename()}`
            await this.saveImage(this.msg.filename(), filename, await this.msg.readyStream())
            // await this.msg.say('图片保存成功！')
        }
    }

    private async saveImage(filename: string, path: string, imgStream: NodeJS.ReadableStream) {
        let fileStream = fs.createWriteStream(path)
        let stream = await imgStream
        return new Promise((resolve, reject) => {
            stream.pipe(fileStream)
            .on('close', () => {
                resolve()
            })
        })

    }

    // private async handleText(text: string) {




    // }


}